package org.peterf.foxish.component;

import org.peterf.foxish.camera.Camera;
import org.peterf.foxish.texture.SlicedTexture;
import org.peterf.foxish.texture.TextureRepository;

public class RectangleGroup extends Geometry {

    protected int sliceX;

    protected int sliceY;

    protected TexturedRectangle[][] items = null;

    protected int resId;

    protected SlicedTexture texture = null;

    public RectangleGroup(int resId, int sliceX, int sliceY) {
        this.resId = resId;
        this.sliceX = sliceX;
        this.sliceY = sliceY;
    }

    @Override
    public void onCreate() {
        texture = TextureRepository.get(resId).slice(sliceX, sliceY);
        items = new TexturedRectangle[sliceX][sliceY];
        for (int i = 0; i < sliceX; ++i) {
            for (int j = 0; j < sliceY; ++j) {
                items[i][j] = new TexturedRectangle(texture, i, j);
                items[i][j].onCreate();
            }
        }
    }

    @Override
    public void onDestroy() {
        for (int i = 0; i < sliceX; ++i) {
            for (int j = 0; j < sliceY; ++j) {
                items[i][j].onDestroy();
            }
        }
        texture.delete();
    }

    @Override
    public void onDraw(Camera camera, float elapsed) {
        for (int i = 0; i < sliceX; ++i) {
            for (int j = 0; j < sliceY; ++j) {
                items[i][j].onDraw(camera, elapsed);
            }
        }
    }

    @Override
    public void onRecreate() {
        texture = TextureRepository.get(resId).slice(sliceX, sliceY);
        for (int i = 0; i < sliceX; ++i) {
            for (int j = 0; j < sliceY; ++j) {
                items[i][j].setTexture(texture);
                items[i][j].onRecreate();
            }
        }
    }

}
